<?php
/*
 * 图片上传类, 对传入的文件进行处理, 主要用于图片上传
 * 不对上传的图片进行缩略图处理, 但是限制上传文件的大小
 * 1. 根据模块对其进行命名
 * 2. 限制上传文件的格式
 * 3. 不生成缩略图, 缩略图使用缩略图工具进行生成, 并后期开发缩略图管理对文件进行管理
 * @package    sys
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 5b48ec162982caf966ef54f8692820628b7324e3 $
 */
defined('IN_IXDCW') or exit('Access Denied');

/**
 * 图片上传
 * Class PictureUpload
 */
class PictureUpload {

	const ERR_OK              = 0;
	const ERR_NO_AUTH         = 21;
	const ERR_MODID_NOT_MATCH = 22;
	const ERR_NOT_WRITEABLE   = 23;
	const ERR_AUTH            = 24;
	const ERR_THUMB_BIG       = 25;
	const ERR_SETTING_LOST    = 26;

	/** @var array 系统错误 */
	protected $arrErr = array(
		// sucess
		'0'   => '文件上传成功',

		// php
		'1'   => '超过服务器允许的大小。',
		'2'   => '超过表单允许的大小。',
		'3'   => '图片只有部分被上传。',
		'4'   => '请选择图片。',
		'6'   => '找不到临时目录。',
		'7'   => '写文件到硬盘出错。',

		'20'  => '文件扩展名格式不正确。',
		'21'  => '您无权上传文件',
		'22'  => '模块信息不匹配!',
		'23'  => '目标目录不可写!',
		'24'  => '非法途径上传!',
		'25'  => '文件大小超出限制!缩略图大小不得大于2M',
		'26'  => '高度宽度信息配置不完整!',

		'999' => '未知错误。',
	);


	/** @var  模块ID */
	protected $moduleid;

	/** @var  模块名称 */
	protected $module;

	/** @var int 时间戳 */
	protected $timestamp;

	/** @var  用户id */
	private $_userid = 0;

	/** @var  用户名 */
	private $_username = '';

	/** @var  用户IP */
	private $_ip;

	/** @var  用户组ID */
	private $_groupid = 3;

	/** @var  扩展文件名 */
	private $_ext;

	/** @var  目标路径 */
	protected  $aimPath;

	/** @var string 错误提示 */
	protected $error = '';

	/** @var string 来源 */
	protected $source = ''; // thumb, editor

	/** @var string session 分组 */
	protected $group = '';

	/** @var int 错误代码号 */
	protected $errno = 0;

	/** @var string 保存的完整路径 */
	protected $url = '';

	protected $session = array();
	/**
	 * 构造函数
	 */
	public function __construct() {
		global $DT_TIME, $DT_IP;
		Session::start();
		$this->timestamp = $DT_TIME;
		$this->_ip        = $DT_IP;
	}

	public function setUserid($userid) {
		if ($userid) {
			$user            = memberinfo($userid, '', '*', 'userid');
			$this->_userid   = $userid;
			$this->_username = $user['username'];
			$this->_groupid  = $user['groupid'];
		}
	}

	public function setSource($moduleid, $source) {
		global $MODULE;
		$this->moduleid = $moduleid;
		$this->module   = $MODULE[$moduleid];
		$this->source    = $source;
		$this->group     = $this->moduleid . '_' . $this->source;
	}


	protected function setErr($errno, $append = '') {
		if (!array_key_exists($errno, $this->arrErr)) {
			$errno = 999;
		}
		$this->errno = $errno;
		$this->error = $this->arrErr[$this->errno] . $append;
	}

	/**
	 * 用于swf 上传
	 * @param $uAuth
	 * @return bool
	 */
	public function checkSwfAuth($uAuth) {
		if (!Auth::checkSwfUpload($this->_userid, $this->_username, $this->_groupid, $uAuth)) {
			$this->setErr(self::ERR_AUTH);
			return false;
		} else {
			return true;
		}
	}


	/** 检查所有权限 */
	protected function _checkAll() {
		// module match, 没有模块 或者模块信息不存在在于系统中
		if (empty($this->moduleid) || empty($this->module)) {
			$this->setErr(self::ERR_MODID_NOT_MATCH, $this->moduleid);
			return false;
		}

		// 没有用户信息
		if (!$this->_userid) {
			$this->setErr(self::ERR_NO_AUTH);
			return false;
		}

		return true;
	}

	/**
	 * 保存图片
	 * 设置表单信息
	 * @param $formData
	 * @return bool
	 * -------------------------------------
	 * [name=>QQ截图20130529115220.png]
	 * [type=>application/octet-stream]
	 * [tmp_name=>D:\wamp\tmp\phpE52E.tmp]
	 * [error=>0]
	 * [size=>6594]
	 * --------------------------------------
	 */
	public function save($formData) {

		//PHP上传失败
		if (!$this->_checkSysUpload($formData)) {
			return false;
		}

		// 权限等等
		if (!$this->_checkAll()) {
			return false;
		}

		// folder check
		if(!$this->_checkFolder($formData)) {
			return false;
		}

		if (Picture::saveFile($formData['tmp_name'], $this->aimPath)) {
			$this->session = array(
				'group' => $this->group,
				'url'   => Picture::url($this->aimPath),
				'time'  => $this->timestamp,
			);
			// 保存到session对象中
			self::saveSession($this->session);
			return true;
		} else {
			$this->setErr(self::ERR_NOT_WRITEABLE, $this->aimPath);
			return false;
		}
	}

	/**
	 * 实际存储图片的地址
	 * @param $formData
	 * @return bool
	 */
	private function _checkFolder($formData) {
		$this->_ext = File::ext($formData['name']);
		$this->aimPath = U::realpath(U::DOMAIN_IMG1) . '/' .Picture::name($this->moduleid, $this->_userid, $this->_ext);

		$folder = dirname($this->aimPath) . '/';
		if (!file_exists($folder)) {
			mkdir($folder, 0777, true);
		}
		if (!File::isWritable($folder)) {
			$this->setErr(self::ERR_NOT_WRITEABLE, array($folder));
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 错误提示
	 * @param string $append
	 */
	protected function error($append = '') {
		exit(json_encode(array('errNo' => $this->errno, 'errMsg' => $this->error . $append)));

	}

	/**
	 * 成功, 返回URL地址
	 */
	protected function ok() {
		exit(json_encode(array('errNo' => self::ERR_OK, 'url' => $this->url)));
	}

	/**
	 * 检测是否出现上传时候的系统错误
	 * @param $file
	 * @return bool
	 */
	protected function _checkSysUpload($file) {
		$errno = $file['error'];
		if ($errno) {
			$this->setErr($errno);
			return false;
		} else {
			return true;
		}
	}


	/**
	 * 保存session
	 * @param $session
	 */
	public static function saveSession($session) {
		Session::start();
		if (!$_SESSION['uploads']) {
			$_SESSION['uploads'] = array();
		}
		$_SESSION['uploads'][] = $session;
	}

	/**
	 * 获取Session分组
	 * @param $group
	 * @return array
	 */
	protected static function getSession($group) {
		Session::start();
		if (!$_SESSION['uploads']) {
			return array();
		}
		return __($_SESSION['uploads'])->filter(function($item) use ($group){
			return $item['group'] == $group;
		});
	}


	/**
	 * 清理掉Session的用户组
	 * @param      $sessionGroup
	 * @param bool $isDelete
	 */
	public static function clearSession($sessionGroup, $isDelete = true) {
		global $_userid;
		Session::start();
		$_SESSION['uploads'] = (array) $_SESSION['uploads'];
		foreach($_SESSION['uploads'] as $key => $picture) {
			if ($picture['group'] == $sessionGroup) {
				unset($_SESSION['uploads'][$key]);
				if ($isDelete) {
					self::deletePicture($picture['url'], $_userid);
				}
			}
		}
	}

	public static function clearPictureSession($url) {
		foreach($_SESSION['uploads'] as $key => $picture) {
			if ($picture['url'] == $url) {
				unset($_SESSION['uploads'][$key]);
			}
		}
	}

	/**
	 * 删除上传的文件
	 * @param $url
	 * @param $userid
	 * @return bool
	 */
	public static function deletePicture($url, $userid) {
		// 是否管理员 ||
		if (!defined('DT_ADMIN') && (!$userid || $userid != Picture::userid($url))) return false;
		// 删除文件
		return Picture::deleteAll($url);
	}
}